package service

import (
	"context"
	"daily-blog/dao"
	"daily-blog/global"
	"daily-blog/model"
	"daily-blog/pkg"
	"fmt"
	"github.com/Tim3Triver/memontago"
)

//CreatePostService 创建post
func CreatePostService(title, desc, content, author, categoryId, category string, tags []model.TagInfo) bool {
	// post 对象
	post := model.Post{
		Title:        title,
		Desc:         desc,
		Content:      content,
		Author:       author,
		CategoryId:   categoryId,
		CategoryName: category,
	}
	// 生成post的uuid
	post.PostId = pkg.GenUUID()
	// 创建post
	if err := dao.CreatePost(&post); err != nil {
		global.GVA_LOG.Error(err.Error())
		return false
	}
	// post关联的tags
	tagNum := len(tags)
	postTags := make([]model.PostTag, tagNum)
	for i := 0; i < tagNum; i++ {
		postTags[i].PostId = post.PostId
		postTags[i].TagId = tags[i].TagId
		postTags[i].TagName = tags[i].TagName
	}

	// 创建PostTags
	ok := CreatePostTags(postTags)
	return ok
}

//DeletePostByIDService 删除post
func DeletePostByIDService(id string) bool {
	// 删除指定post
	if err := dao.DeletePostByID(id); err != nil {
		global.GVA_LOG.Error(err.Error())
		return false
	}
	// 删除post对应的tags
	return DeletePostTagsByPostId(id)
}

//UpdatePostByIdService 更新post
func UpdatePostByIdService(id, title, desc, content, categoryId, category string, tags []model.TagInfo) bool {
	// 查找文章是否存在
	postContent, err := dao.GetPostByID(id)
	if err != nil || postContent == "" {
		global.GVA_LOG.Error(err.Error())
		global.GVA_LOG.Error(fmt.Sprintf("postContent:%v.", postContent))
		return false
	}

	// 设置更新后的文章内容
	var post model.Post
	post.PostId = id
	post.Title = title
	post.Desc = desc
	post.Content = content
	post.CategoryId = categoryId
	post.CategoryName = category

	// 更新post内容
	err = dao.UpdatePost(&post)
	if err != nil {
		global.GVA_LOG.Error(err.Error())
		return false
	}

	// 更新tags内容
	//1.删除原tag
	DeletePostTagsByPostId(id)
	//2.添加新tag
	var postTags = make([]model.PostTag, len(tags))
	for i := 0; i < len(postTags); i++ {
		postTags[i] = model.PostTag{
			PostId:  id,
			TagId:   tags[i].TagId,
			TagName: tags[i].TagName,
		}
	}
	ok := CreatePostTags(postTags)
	return ok
}

// GetPostByIDService 获取指定post
func GetPostByIDService(id string) (model.PostInfo, bool) {
	var postInfo model.PostInfo
	postContent, err := dao.GetPostByID(id)
	if err != nil {
		global.GVA_LOG.Error(err.Error())
		return postInfo, false
	}
	like, watch, _ := GetLikeWatch(id)
	// 组合并返回
	// 获取点赞量，浏览量
	postInfo.Content = postContent
	postInfo.Watch = watch
	postInfo.Like = like

	// 增加一次浏览
	AddCount(id, 2)
	return postInfo, true
}

// GetPostListService 获取post列表 不含有文章内容
func GetPostListService() (postList []model.PostWithoutContent, ok bool) {
	// 获取文章列表
	postList, err := dao.GetPostList()
	if err != nil {
		global.GVA_LOG.Error(err.Error())
		return nil, false
	}
	// 将文章所发布时间改为 几分钟之前的格式
	for i := 0; i < len(postList); i++ {
		postList[i].CreateTime, err = memontago.Parse(postList[i].CreatedAt)
		if err != nil {
			global.GVA_LOG.Error(err.Error())
		}
	}
	// 获取文章的对应的tags
	ok = GetPostTags(postList)
	return postList, true
}

// GetPostListByCategoryId 根据目录id获取所有的文章
// 会报错，gorm 映射问题
func GetPostListByCategoryId(categoryId string) (postList []model.PostWithoutContent, ok bool) {
	postList, err := dao.GetPostListByCategoryId(categoryId)
	if err != nil {
		global.GVA_LOG.Error(err.Error())
		return nil, false
	}
	ok = GetPostTags(postList)
	return
}

// GetPostListByTagId 根据标签id获取所有的文章
func GetPostListByTagId(tagId string) (postList []model.PostWithoutContent, ok bool) {
	postIds, err := dao.GetPostIDListByTagId(tagId)
	if err != nil {
		global.GVA_LOG.Error(err.Error())
		return nil, false
	}
	postList, err = dao.GetPostListByIds(postIds)
	if err != nil {
		global.GVA_LOG.Error(err.Error())
		return nil, false
	}
	if ok = GetPostTags(postList); !ok {
		return nil, false
	}

	return
}

// GetPostTags 为文章查询并添加tags
func GetPostTags(posts []model.PostWithoutContent) bool {
	// 获取postids
	postIds := make([]string, len(posts))
	for i := 0; i < len(posts); i++ {
		postIds[i] = posts[i].PostId
	}
	postIdTags, err := dao.GetPostTagsByPostIds(postIds)
	if err != nil {
		global.GVA_LOG.Error(err.Error())
		return false
	}
	postIdTagsMap := make(map[string][]model.TagInfo)
	for i := 0; i < len(postIdTags); i++ {
		postIdTagsMap[postIdTags[i].PostId] = append(postIdTagsMap[postIdTags[i].PostId], model.TagInfo{TagId: postIdTags[i].TagId, TagName: postIdTags[i].TagName})
	}
	for i := 0; i < len(posts); i++ {
		posts[i].Tags = postIdTagsMap[posts[i].PostId]
	}
	return true
}

// GetLikeWatch 获取点赞量，获取浏览量
func GetLikeWatch(postId string) (like string, watch string, ok bool) {
	ctx := context.Background()
	like, err := global.GVA_RDB.Get(ctx, postId+":like").Result()
	if err != nil {
		global.GVA_LOG.Error(err.Error())
		return "0", "0", false
	}
	watch, err = global.GVA_RDB.Get(ctx, postId+":watch").Result()
	if err != nil {
		global.GVA_LOG.Error(err.Error())
		return "0", "0", false
	}
	return like, watch, true
}

// AddCount 增加计数
func AddCount(postId string, t int) bool {
	ctx := context.Background()
	var err error
	switch t {
	case 1: // 增加点赞
		err = global.GVA_RDB.Incr(ctx, postId+":like").Err()
	case 2: // 增加watch
		err = global.GVA_RDB.Incr(ctx, postId+":watch").Err()
	}
	if err != nil {
		return false
	}
	return true
}
